package com.jasonchoi.security.commons.security.authentication;

import cn.hutool.core.util.StrUtil;
import com.jasonchoi.security.commons.base.BaseRestResult;
import com.jasonchoi.security.commons.utils.JwtUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功 handler
 */
@Log4j2
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Value("${global.jwt.header}")
    private String jwtHeader;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        UserDetails userDetail = (UserDetails) authentication.getPrincipal();
        JwtUtil.JwtInfo jwtInfo = new JwtUtil.JwtInfo().setUsername(userDetail.getUsername())
                                                       .setRole(StrUtil.join(",", userDetail.getAuthorities()));
        String jwtStr = JwtUtil.generateJwt(jwtInfo);
        log.debug("生成的JWT： " + jwtStr);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.setHeader(jwtHeader, jwtStr);
        response.getWriter().write(BaseRestResult.ok("登录成功").toJson());
    }
}

